package com.kingsoft.dc.khaos.plugin.core;

import com.kingsoft.dc.khaos.plugin.core.metadata.PluginModuleConfig;
import com.kingsoft.dc.khaos.plugin.core.utils.AppConfigParse;
import com.kingsoft.dc.khaos.plugin.core.utils.Logging;

import java.util.List;
import java.util.Properties;

/**
 * 任务Context.
 */
public class KhaosContext extends Logging {

    //引擎信息
    private KhaosConf _conf;
    private KhaosEnv _env;

    private String _applicationId = "1";

    private List<PluginModuleConfig> moduleConfigList;

    //启动类
    private AppScheduler _appScheduler;

    //获取方法
    public KhaosConf conf() {
        return _conf;
    }

    //获取方法
    public KhaosConf getConf() {
        return _conf;
    }

    public AppScheduler getScheduler(){return  _appScheduler;}

    public KhaosEnv env() {
        return _env;
    }

    public void initJson() throws Exception {
        String jsonConf = _conf.getString("khaos.app.json", "");
        if ("".equals(jsonConf)) {
            throw new Exception("参数设置");
        }
        AppConfigParse appConfigParse = new AppConfigParse(_conf);
        moduleConfigList = appConfigParse.parseJson(jsonConf);
    }


    public void loadSystemEnv() {
        Properties sysProps = System.getProperties();
        for (Object key : sysProps.keySet()) {
            if (key.toString().startsWith("khaos.")) {
                if (!_conf.contains(key.toString())) {
                    _conf.set(key.toString(), sysProps.getProperty(key.toString()));
                }
            }
        }
    }

    public KhaosEnv createKhaosEnv(KhaosConf conf) {
        return KhaosEnv.createEnv(_applicationId, conf, moduleConfigList);
    }

    public void runApp() {
        try {
            getScheduler().run(env().getDittoInfo().get(0));
        } catch (Exception ex) {
            logError("Error run Khaos." + ex);
            try {
                stop();
                System.exit(-1);
            } catch (Exception e){
                if (e instanceof InterruptedException) {
                    logError("Error stopping KhaosContext after init error." + e.toString());
                }
            } finally{
                System.exit(-1);
            }
        }
    }

    public KhaosContext(KhaosConf config) {
        //初始化Context
        try {
            _conf = config;
            loadSystemEnv();
            _conf.validateSettings();
            _appScheduler = new AppScheduler(this);
            initJson();
            _env = createKhaosEnv(_conf);
            KhaosEnv.set(_env);

        } catch (Exception e) {
            logError("Error initializing KhaosContext." + e.toString());
        } finally{
//                throw e;
        }
    }

    //停止所有组件和线程
    public void stop() {
    }
}
